/*
 * Copyright (c) 2013-2015 Charkey. All rights reserved.
 *
 * This software is the confidential and proprietary information of Charkey.
 * You shall not disclose such Confidential Information and shall use it only
 * in accordance with the terms of the agreements you entered into with Charkey.
 *
 * Charkey MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
 *
 * Charkey SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING,
 * MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
 */

package cn.simastudio.talos.core.service.base.impl;

import cn.simastudio.talos.core.mapper.base.ConfigDataMapper;
import cn.simastudio.talos.core.model.base.ConfigData;
import cn.simastudio.talos.core.service.base.ConfigDataService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Usage: 配置数据缓存Service实现类
 *
 * @author Charkey
 * @date 2015/6/26 20:00
 */
@Service
@SuppressWarnings("SpringJavaAutowiringInspection")
public class ConfigDataServiceImpl implements ConfigDataService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ConfigDataServiceImpl.class);

    private Cache configurationCache;

    @Autowired
    private ConfigDataMapper configDataMapper;

    @Autowired
    public ConfigDataServiceImpl(CacheManager cacheManager) {
        this.configurationCache = cacheManager.getCache("configurationCache");
    }

    public ConfigDataServiceImpl() {
    }

    @Override
    public void loadConfigDataFromDatabase() {
        // 清空原有缓存数据
        configurationCache.clear();
        // 重新加载数据库配置数据
        List<ConfigData> configDataList = configDataMapper.getAllConfigData();
        for (ConfigData configData : configDataList) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Load configuration data from db. key={}, value={}", configData.getConfigName(), configData.getConfigValue());
            }
            configurationCache.put(configData.getConfigName(), configData.getConfigValue());
        }
    }
}
